const DownloadManager = plus.android.importClass('android.app.DownloadManager');
const Uri = plus.android.importClass('android.net.Uri');
const Context = plus.android.importClass('android.content.Context');
const BroadcastReceiver = plus.android.importClass('android.content.BroadcastReceiver');
const File = plus.android.importClass('java.io.File');
const IntentFilter = plus.android.importClass('android.content.IntentFilter');
import common from './common.js'
export default {
	//下载APK
	downloadAPK(versionUrl, versionName) {
		const main = plus.android.runtimeMainActivity();
		//创建下载任务
		let request = new DownloadManager.Request(Uri.parse(versionUrl));
		//在通知栏中显示
		request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
		request.setTitle(`${common.version.name}更新下载中...`);
		request.setVisibleInDownloadsUi(true);
		//保存目录
		const saveFolder = `_doc/Download/${versionName}`;
		const file = new File(plus.io.convertLocalFileSystemURL(saveFolder))
		request.setDestinationUri(Uri.fromFile(file));
		//将下载请求加入下载队列
		const downloadManager = main.getSystemService(Context.DOWNLOAD_SERVICE);
		downloadManager.enqueue(request);
		common.updating = true; //设置下载中
		const receiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
			onReceive: (context, intent) => {
				common.updating = false;
				if (file.exists()) {
					common.execDelay(() => {
						plus.push.createMessage(`${common.version.name}最新版已下载完毕，请点击安装`, {
							type: 5, //安装类型
							filePath: file.getAbsolutePath()
						}, {
							title: common.version.name
						});
						uni.showConfirm({
							content: '最新版本已下载完毕，您是否现在安装？',
							confirmVal: '是',
							cancelVal: '否'
						}).then(() => {
							plus.runtime.install(file.getAbsolutePath());
						});
					}, 'DownloadAPK', 1000);
				}
			}
		});
		main.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}
}
